package org.com.controller;

import org.com.common.R;
import org.com.pojo.ChatMessage;
import org.com.pojo.Users;
import org.com.service.ChatService;
import org.com.service.UsersService;
import org.com.util.AliOssUtil;
import org.com.websocket.ChatWebSocketHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/chat")
public class ChatController {
    
    private static final Logger log = LoggerFactory.getLogger(ChatController.class);
    
    @Autowired
    private ChatService chatService;
    
    @Autowired
    private UsersService usersService;
    
    @Autowired
    private ChatWebSocketHandler chatWebSocketHandler;
    
    @Autowired
    private AliOssUtil aliOssUtil;
    
    @GetMapping("/experts/online")
    public R getOnlineExperts() {
        try {
            // 获取所有专家ID
            List<Integer> expertIds = usersService.getExpertUserIds();
            if (expertIds.isEmpty()) {
                return R.success("暂无专家", new ArrayList<>());
            }

            // 获取在线用户列表
            Set<Integer> onlineUserIds = chatWebSocketHandler.getOnlineUsers();
            System.out.println("当前在线用户: " + onlineUserIds);

            // 获取在线专家信息
            List<Users> onlineExperts = expertIds.stream()
                    .filter(onlineUserIds::contains)  // 只保留在线的专家
                    .map(id -> usersService.getById(id))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            System.out.println("找到在线专家: " + onlineExperts.size() + " 个");
            onlineExperts.forEach(expert -> 
                System.out.println("在线专家 - ID: " + expert.getUserId() + ", 名称: " + expert.getUserName())
            );
            
            if (onlineExperts.isEmpty()) {
                return R.success("暂无在线专家", new ArrayList<>());
            }
            return R.success("获取在线专家列表成功", onlineExperts);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取在线专家列表失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/experts/{expertId}")
    public R getExpertInfo(@PathVariable Integer expertId) {
        try {
            Users expert = usersService.getById(expertId);
            if (expert == null) {
                return R.error("专家不存在");
            }
            return R.success("获取专家信息成功", expert);
        } catch (Exception e) {
            return R.error("获取专家信息失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/history/{expertId}")
    public R getChatHistory(@PathVariable Integer expertId, @RequestParam Integer userId) {
        try {
            List<ChatMessage> messages = chatService.getChatHistory(userId, expertId);
            if (messages.isEmpty()) {
                return R.success("暂无聊天记录", new ArrayList<>());
            }
            return R.success("获取聊天记录成功", messages);
        } catch (Exception e) {
            return R.error("获取聊天记录失败：" + e.getMessage());
        }
    }
    
    @PostMapping("/mark-read/{expertId}")
    public R markAsRead(@PathVariable Integer expertId, @RequestParam Integer userId) {
        try {
            boolean success = chatService.markAsRead(userId, expertId);
            return success ? R.success("标记消息已读成功") : R.error("标记消息已读失败");
        } catch (Exception e) {
            return R.error("标记消息已读失败：" + e.getMessage());
        }
    }
    
    @GetMapping("/unread-count/{expertId}")
    public R getUnreadCount(@PathVariable Integer expertId, @RequestParam Integer userId) {
        try {
            int count = chatService.getUnreadCount(userId);
            return R.success("获取未读消息数成功", count);
        } catch (Exception e) {
            return R.error("获取未读消息数失败：" + e.getMessage());
        }
    }

    @PostMapping("/upload/image")
    public R uploadChatImage(@RequestParam("image") MultipartFile image, HttpServletRequest request) {
        try {
            // 获取当前用户ID
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute("userId") == null) {
                log.error("用户未登录");
                return R.error("请先登录");
            }
            Integer userId = (Integer) session.getAttribute("userId");
            log.info("当前用户ID: {}", userId);

            if (image == null || image.isEmpty()) {
                log.error("上传失败：文件为空");
                return R.error("请选择要上传的图片");
            }

            // 检查文件类型
            String contentType = image.getContentType();
            log.info("上传文件类型: {}", contentType);
            if (contentType == null || !contentType.startsWith("image/")) {
                log.error("上传失败：文件类型错误 {}", contentType);
                return R.error("只能上传图片文件");
            }

            // 检查文件大小（5MB）
            long maxSize = 5 * 1024 * 1024;
            long fileSize = image.getSize();
            log.info("文件大小: {} bytes", fileSize);
            if (fileSize > maxSize) {
                log.error("上传失败：文件过大 {} bytes", fileSize);
                return R.error("图片大小不能超过5MB");
            }

            log.info("开始上传文件到OSS，原始文件名: {}", image.getOriginalFilename());
            // 上传到阿里云OSS
            String imageUrl = aliOssUtil.upload(image);
            log.info("文件上传成功，URL: {}", imageUrl);
            
            return R.success("图片上传成功", imageUrl);
        } catch (Exception e) {
            log.error("图片上传失败", e);
            return R.error("图片上传失败：" + e.getMessage());
        }
    }
} 